<template>
	<view class="view-root">
		<scroll-view class="content-scroll" scroll-y="true">
			<view class="scroll-flex-wrap">
				<view class="address-wrap" @click="gotoRouter('/pages-member/addressList/addressList?type=1')">
					<image src="https://res.jiuzhang-cloud.com/jzy-oss/upload/image/dti-hospital/ic_order_address.png"></image>
					<view class="address-text-wrap">
						<view v-if="userAddress" class="address-text">收货人：{{ userAddress.name }}&nbsp;&nbsp;{{ userAddress.phone }}</view>
						<view v-if="userAddress" class="address-text" style="margin-top: 16rpx;">
							收货地址：{{ userAddress.province != userAddress.city ? userAddress.province : '' }}{{ userAddress.city }}{{ userAddress.district
							}}{{ userAddress.address }}
						</view>
						<view class="address-text" v-if="!userAddress">您还没有选择地址，请选择地址</view>
					</view>
				</view>
				<view v-for="(store, index) in orderInfo.commodityDrugstoreGroup" :key="index" class="store-wrap">
					<view class="store-title">
						<image src="https://res.jiuzhang-cloud.com/jzy-oss/upload/image/dti-hospital/ic_store_location.png"></image>
						<view class="store-title-text">{{store.merchantName}}</view>
					</view>
					<view v-for="(medicine, index) in store.commodityInfo" :key="index" class="valid-medicine" @click="gotoRouter('/pages-mall/medicineDetail/medicineDetail?id=' + medicine.id)">
						<view class="medicine-pic-wrap">
							<image :src="medicine.thumbnailUrl" class="medicine-pic"></image>
							<view v-if="medicine.recipeFlag > 0" class="prescription-tag">处方药</view>
						</view>
						<view class="info-wrap">
							<view class="medicine-name nowrap">{{medicine.name}}</view>
							<view class="medicine-pack">规格：{{medicine.specification}}</view>
						</view>
						<view class="price-count-wrap">
							<view class="medicine-price">￥{{medicine.salesPrice}}</view>
							<view class="medicine-count">×{{medicine.count}}</view>
						</view>
					</view>
					<view class="store-form-line">
						<view class="store-form-title">配送方式</view>
						<view style="flex: 1;"></view>
						<view v-if="store.distributionModeVo.allowExpress > 0" :class="store.receivingWay == 1 ? 'distribution_checked': 'distribution_normal'" @click="checkExpress(store)">快递配送</view>
						<view v-if="store.distributionModeVo.allowComeHere > 0" :class="store.receivingWay == 2 ? 'distribution_checked': 'distribution_normal'" @click="checkSelf(store)">到店自提</view>
					</view>
					<view v-if="store.receivingWay == 2" class="store-form-line">
						<view class="store-form-title">提货人</view>
						<input class="form_input" style="flex: 1;" placeholder-style="color:#B0B2B1" placeholder="请输入" maxlength="15" type="text"
							v-model="store.consigneeName"></input>
					</view>
					<view v-if="store.receivingWay == 2" class="store-form-line">
						<view class="store-form-title">提货电话</view>
						<input class="form_input" style="flex: 1;" placeholder-style="color:#B0B2B1" placeholder="请输入" maxlength="11" type="number"
							v-model="store.consigneeTel"></input>
					</view>
					<view v-if="store.receivingWay == 1" class="store-form-line">
						<view class="store-form-title">配送运费</view>
						<view class="store-form-content" style="flex: 1;">{{store.expressNotice}}</view>
					</view>
					<view class="store-form-line" @click="showCoupons(store)">
						<image style="width: 32rpx;height: 26rpx;margin-right: 8rpx;" src="https://res.jiuzhang-cloud.com/jzy-oss/upload/image/dti-hospital/ic_coupon.png"></image>
						<view class="store-form-title">优惠券</view>
						<view v-if="!store.selectCoupon" style="flex: 1;"></view>
						<view class="form_no_content">{{couponsForChoose.length == 0 ? '暂无可用': (store.selectCoupon ? store.selectCoupon.name: "请选择优惠券")}}</view>
						<view v-if="store.selectCoupon" class="coupon-price">-￥{{store.selectCoupon.money}}</view>
						<image style="width: 46rpx;height: 46rpx;" src="https://res.jiuzhang-cloud.com/jzy-oss/upload/image/dti-hospital/ic_gray_right.png"></image>
					</view>
					<view class="store-form-line">
						<view class="store-form-title">订单备注</view>
						<input class="form_input" style="flex: 1;" placeholder-style="color:#B0B2B1" placeholder="选填，请先与客服协商一致" maxlength="150" type="text"
							v-model="store.remark"></input>
					</view>
					<view class="store-price-line">
						<view class="store-medicine-count">共{{store.subCount}}件</view>
						<view class="store-price-title">小计：</view>
						<view class="store-price-show">￥{{getStorePrice(store)}}</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="bottom-panel">
			<view class="total-medicine-count">共{{orderInfo.totalCount}}件</view>
			<view class="total-price-title">合计：</view>
			<view class="total-price-show">￥{{getTotalPrice()}}</view>
			<view class="confirm-btn" @click="doConfirm">去支付</view>
		</view>
		<view v-if="couponsVisible" class="coupon-page-wrap">
			<view class="outer-area" @click="showCoupons"></view>
			<view class="coupons-panel">
				<view class="coupon-panel-title">可用优惠券</view>
				<scroll-view scroll-y="true" :style="{height: `${couponPanelHeight}rpx`}">
					<view v-for="(coupon, index) in couponsForChoose" :key="index" class="coupon-wrap">
						<view class="coupon-value-wrap">
							<view class="coupon-value-text">￥{{coupon.money}}</view>
							<view class="coupon-threshold-text">满{{coupon.reachMoney}}可用</view>
						</view>
						<view class="coupon-info-wrap">
							<view class="coupon-name">{{coupon.name}}</view>
							<view class="coupon-type">{{coupon.useTypeName}}</view>
							<view class="coupon-type">{{coupon.expireTime}}</view>
						</view>
						<view class="coupon-choose-btn" @click="chooseCoupon(coupon)">立即使用</view>
					</view>
				</scroll-view>
				<image src="https://res.jiuzhang-cloud.com/jzy-oss/upload/image/dti-hospital/ic_float_close.png" @click="showCoupons"></image>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapState, mapMutations } from 'vuex';
	export default {
		data() {
			return {
				sourceMedicine: [],
				orderCode: null,
				orderInfo: {},
				couponsVisible: false,
				couponPanelHeight: 0,
				couponsForChoose: [],
				handleStore: {},
				payFlag: true //支付按钮开关
			};
		},
		onLoad(params) {
			if (params.orderCode) {
				this.orderCode = params.orderCode;
			} else {
				this.sourceMedicine = JSON.parse(params.medicines);
			}
			this.queryOrderInfo();
			if (!this.userAddress) {
				this.addressList();
			}
		},
		computed: {
			...mapState({
				userAddress: state => state.userAddress
			})
		},
		watch: {
			userAddress(e){
				if (this.orderInfo.commodityDrugstoreGroup) {
					this.orderInfo.commodityDrugstoreGroup.forEach(store => {
						if (store.receivingWay == 1) {
							this.queryExpressPrice(store);
						}
					})
				}
			}
		},
		methods: {
			...mapMutations({
				setUserAddress: 'setUserAddress'
			}),
			showCoupons(store = null) {
				if (store && !this.couponsVisible) {
					this.handleStore = store;
					let couponsShow = [];
					store.couponList.forEach(coupon => {
						let hasConflict = false;
						this.orderInfo.commodityDrugstoreGroup.forEach(e => {
							if (e.selectCoupon && e.selectCoupon.id == coupon.id) {
								hasConflict = true;
							}
						})
						if (!hasConflict) {
							couponsShow.push(coupon);
						}
					})
					this.couponsForChoose = couponsShow;
					this.couponPanelHeight = this.couponsForChoose.length * 235 > 800 ? 800 : this.couponsForChoose.length * 235;
				}
				this.couponsVisible = !this.couponsVisible;
			},
			chooseCoupon(coupon) {
				this.handleStore.selectCoupon = coupon;
				this.handleStore.couponGrantId = coupon.id;
				this.couponsVisible = false;
				this.$forceUpdate();
			},
			getStorePrice(store) {
				if (!store.freightAmount) {
					store.freightAmount = 0.00;
				}
				if (store.selectCoupon) {
					let price = Number(parseFloat(store.subTotalPrice) + store.freightAmount - parseFloat(store.selectCoupon.money));
					if (price < 0) {
						price = 0.00
					}
					return price.toFixed(2);
				} else {
					return Number(parseFloat(store.subTotalPrice) + store.freightAmount).toFixed(2);
				}
			},
			getTotalPrice() {
				if (this.orderInfo.commodityDrugstoreGroup) {
					let price = 0.00;
					this.orderInfo.commodityDrugstoreGroup.forEach(store => {
						price += parseFloat(this.getStorePrice(store));
					})
					if (price < 0) {
						price = 0.00
					}
					return price.toFixed(2);
				} else {
					return "0.00";
				}
			},
			//地址列表
			addressList() {
				this.$api.addressList({}).then(res => {
					if (res.code == 200) {
						this.setUserAddress(res.result[0]);
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						});
					}
				});
			},
			queryOrderInfo() {
				if (this.orderCode) {
					this.$api.getOrderCreateBase({
						data: {
							orderCode: this.orderCode
						}
					}).then(res => {
						if (res.code == 200) {
							if (res.result.detailData.status != 100) {
								// 不是待支付状态就直接跳转订单详情
								uni.redirectTo({
									url: '/pages-order/orderDetail/orderDetail?code=' + this.orderCode
								})
							} else {
								this.orderInfo = res.result;
								if (res.result.detailData.receivingWay == 1) {
									this.orderInfo.commodityDrugstoreGroup[0].receivingWay = 1;
									// this.orderInfo.commodityDrugstoreGroup[0].freightAmount = parseFloat(res.result.detailData.freightAmount);
									// this.orderInfo.commodityDrugstoreGroup[0].expressNotice = res.result.detailData.freightAmount;
									this.orderInfo.commodityDrugstoreGroup[0].remark = res.result.detailData.remark;
									this.orderInfo.userAddress = res.result.detailData.userAddress;
									if (res.result.detailData.couponGrantId) {
										this.orderInfo.commodityDrugstoreGroup[0].couponList.forEach(coupon => {
											if (coupon.id == res.result.detailData.couponGrantId) {
												this.orderInfo.commodityDrugstoreGroup[0].selectCoupon = coupon;
												this.orderInfo.commodityDrugstoreGroup[0].couponGrantId = res.result.detailData.couponGrantId;
											}
										})
									}
									this.queryExpressPrice(this.orderInfo.commodityDrugstoreGroup[0]);
								} else {
									this.orderInfo.commodityDrugstoreGroup[0].receivingWay = 2;
									this.orderInfo.commodityDrugstoreGroup[0].consigneeName = res.result.detailData.userAddress.name;
									this.orderInfo.commodityDrugstoreGroup[0].consigneeTel = res.result.detailData.userAddress.phone;
									this.orderInfo.commodityDrugstoreGroup[0].remark = res.result.detailData.remark;
								}
							}
						} else {
							uni.showToast({
								title: res.message,
								icon:'none'
							})
						}
					})
				} else {
					let requestList = [];
					this.sourceMedicine.forEach((item, index) => {
						requestList.push({
							id: item.id,
							count: item.count
						})
					})
					this.$api.getOrderCreateBase({
						data: {
							commodityInfo: requestList
						}
					}).then(res => {
						if (res.code == 200) {
							this.orderInfo = res.result;
						} else {
							uni.showToast({
								title: res.message,
								icon:'none'
							})
							uni.navigateBack({
								delta: 1
							})
						}
					})
				}
			},
			checkExpress(store) {
				if (store.receivingWay == 1) {
					store.receivingWay = 0;
					store.freightAmount = 0.00;
				} else {
					store.receivingWay = 1;
				}
				this.$forceUpdate();
				this.queryExpressPrice(store);
			},
			checkSelf(store) {
				if (store.receivingWay == 2) {
					store.receivingWay = 0;
				} else {
					store.receivingWay = 2;
					if (!store.consigneeName) {
						store.consigneeName = this.orderInfo.consigneeName;
					}
					if (!store.consigneeTel) {
						store.consigneeTel = this.orderInfo.consigneeTel;
					}
					store.freightAmount = 0.00;
				}
				this.$forceUpdate();
			},
			queryExpressPrice(store) {
				this.$api.countExpressPrice({
					data: {
						commodityInfo: store.commodityInfo,
						cityCode: this.userAddress.cityCode
					}
				}).then(res => {
					if (res.code == 200) {
						if (res.result.errorMsg) {
							store.expressNotice = res.result.errorMsg;
							store.freightAmount = 0.00;
						} else {
							store.expressNotice = "￥" + res.result.freightAmountInfo;
							store.freightAmount = parseFloat(res.result.freightAmountInfo);
						}
					} else {
						store.freightAmount = 0.00;
					}
					this.$forceUpdate();
				})
			},
			doConfirm() {
				let notFinish = false;
				for(let store of this.orderInfo.commodityDrugstoreGroup) {
					if (!store.receivingWay || store.receivingWay == 0) {
						uni.showToast({
							title: '请选择配送方式',
							icon:'none'
						})
						notFinish = true;
						break;
					} else if (store.receivingWay == 2 && (store.consigneeName == '' || store.consigneeTel == '')) {
						uni.showToast({
							title: '到店自提请将提货信息填写完全',
							icon:'none'
						})
						notFinish = true;
						break;
					}
				}
				if (!notFinish) {
					let params = {
							userAddress: this.userAddress,
							commodityDrugstoreGroup: this.orderInfo.commodityDrugstoreGroup
						}
					if (this.orderCode) {
						params.orderCode = this.orderCode;
					}
					this.$api.createOrder({
						data: params
					}).then(res => {
						if (res.code == 200) {
							this.submitOrder(res.result.orderCodes);
						} else {
							uni.showToast({
								title: res.message,
								icon:'none'
							})
						}
					})
				}
			},
			
			//发起微信支付
			submitOrder(orderCodes) {
				if (this.payFlag) {
					this.payFlag = false;
					this.$api
						.payOrder({
							data: {
								codeList: orderCodes
							}
						})
						.then(res => {
							if (res.code == 200) {
								if (res.result == null) {
									// code == 200 且 result为空的情况代表只支付0元，直接跳过支付流程
									uni.showToast({
										title: res.message,
										icon: '支付成功'
									});
									uni.redirectTo({
										url: '/pages-order/orderDetail/orderDetail?code=' + orderCodes[0]
									})
								} else {
									this.wxRequestPayment(res.result, orderCodes[0]);
								}
							} else {
								uni.showToast({
									title: res.message,
									icon: 'none'
								});
							}
						});
				}
			},
			
			//微信小程序拉起支付
			wxRequestPayment(res, orderCode) {
				wx.requestPayment({
					timeStamp: res.timeStamp,
					nonceStr: res.nonceStr,
					package: res.packageValue,
					signType: res.signType,
					paySign: res.paySign,
					success: success => {
						uni.showToast({
							title: '支付成功',
							icon: 'none'
						});
						uni.redirectTo({
							url: '/pages-order/orderDetail/orderDetail?code=' + orderCode
						})
					},
					fail: error => {
						uni.showToast({
							title: '取消支付',
							icon: 'none'
						});
						uni.redirectTo({
							url: '/pages-order/orderDetail/orderDetail?code=' + orderCode
						})
					},
					complete: () => {
						this.payFlag = true;
					}
				});
			}
		}
	}
</script>

<style lang="less" scoped>
@import './orderCreate.less';

</style>
